package com.xiehua.task.server;

import java.util.HashMap;
import java.util.Map;

import com.xiehua.task.agent.PostMan;
import com.xiehua.task.intf.AbsBusinessHandler;
import com.xiehua.task.prop.XiehuaConfig;
import com.xiehua.task.protocol.Type;
import com.xiehua.task.protocol.TaskPacket;
import com.xiehua.task.server.handler.BindClientHandler;
import com.xiehua.task.server.handler.TaskPushRespHandler;
import com.xiehua.task.server.handler.TaskRegReqHandler;
import com.xiehua.task.server.handler.TaskexEcuteCompleteReqHandler;
import com.xiehua.task.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioHandler;

/**
 *
 * @author tanyaowu
 *
 */
public class ServerHandler extends PostMan implements ServerAioHandler {

	private static Logger log = LoggerFactory.getLogger(ServerHandler.class);

	private static Map<Byte, AbsBusinessHandler<?>> handlerMap;
	static {
		handlerMap = new HashMap<>();
		handlerMap .put(Type.BIND_CLIENT,new BindClientHandler());
		handlerMap .put(Type.TASK_REG_REQ,new TaskRegReqHandler());
		handlerMap .put(Type.TASK_PUSH_RESP,new TaskPushRespHandler());
		handlerMap .put(Type.TASK_EXECUTE_COMPLETE_REQ,new TaskexEcuteCompleteReqHandler());
	}

	/**
	 * 处理消息
	 */
	@Override
	public void handler(Packet packet, ChannelContext channelContext) throws Exception {
		TaskPacket xiehuakPacket = (TaskPacket) packet;
		Byte type = xiehuakPacket.getType();
		if(Type.HEART_BEAT_REQ == type.byteValue()) return;
		//valida data
		if(xiehuakPacket.getSignData() == null) {
			log.warn("消息包sign缺失");
			return;
		}
		if(StringUtils.isEmpty(xiehuakPacket.getClientId())){
			log.warn("消息包cid缺失");
			return;
		}
		String secretKey = XiehuaConfig.getInstance().get(xiehuakPacket.getClientId());
		if(StringUtils.isEmpty(secretKey)){
			log.error("cid:{}对应的secretKey为空",xiehuakPacket.getClientId());
			return;
		}
		if(!xiehuakPacket.getSignData().equals(xiehuakPacket.signData(secretKey))){
			log.warn("风险:消息被篡改");
			return;
		}
		AbsBusinessHandler<?> bsHandler = handlerMap.get(type);
		if (bsHandler == null) {
			log.error("{}, 找不到处理类，type:{}", channelContext, type);
			return;
		}
		bsHandler.handler(xiehuakPacket, channelContext);
		return;
	}
}
